/**
 * 通过net.Server类来创建一个TCP服务器
 */

/* 引入net模块 */
var net = require("net");

/* 实例化一个服务器对象 */
var server = new net.Server();


//聚合所有客户端
var sockets = []; 
/* 监听 connection 事件 */
server.on("connection", function (socket) {
    console.log("someone connects");
	sockets.push(socket);
	/* 设置最大连接数量 */
    server.maxConnections=3;
    server.getConnections(function(err,count){
        console.log("the count of client is "+count);
    })
	
	var address = server.address();
    var message = "the server address is"+JSON.stringify(address);

    /* 发送数据 */
    socket.write(message,function(){
        var writeSize = socket.bytesWritten;
        console.log(message + "has send");
        console.log("the size of message is"+writeSize);
    })

    /* 监听data事件 */
    socket.on('data',function(data){
        console.log(data.toString());
        var readSize = socket.bytesRead;
        console.log("the size of data is"+readSize);

        sockets.forEach(function(otherSocket){
                if (otherSocket !== socket){
                    //var hex=new Buffer(data,"binary")
                    otherSocket.write(data,"hex");
                    console.log("已发送")
                }
            }); 
    })


});

/* 获取地址信息 */
server.listen(8000,function(){
    /* 获取地址信息，得到的是一个json { address: '::', family: 'IPv6', port: 8000 } */
    var address = server.address();
    
    /* TCP服务器监听的端口号 */
    console.log("the port of server is"+ address.port);

    /* TCP服务器监听的地址 */
    console.log("the address of server is"+ address.address);

    /* 说明TCP服务器监听的地址是 IPv6 还是 IPv4 */
    console.log("the family of server is"+ address.family);
})

/* 设置监听时的回调函数 */
server.on("listening", function () {
    
})

/* 设置关闭时的回调函数 */
server.on("close", function () {
    console.log("server closed!");
})

/* 设置错误时的回调函数 */
server.on("error", function (err) {
    console.log("error!");
})